package com.ziyun.pop.modules.logistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.utility.New;
import com.utility.StringUtils;
import com.ziyun.pop.common.e.logistics.LogisticFinanceStatusEnum;
import com.ziyun.pop.common.utils.UserUtils;
import com.ziyun.pop.modules.erpOrderLog.service.ErpOrderLogService;
import com.ziyun.pop.modules.logistics.dao.ErpLogisticsDao;
import com.ziyun.pop.modules.logistics.dto.LogisticsReceiverDto;
import com.ziyun.pop.modules.logistics.dto.LogisticsShipperDto;
import com.ziyun.pop.modules.logistics.dto.TwbLogisticsPaymentDto;
import com.ziyun.pop.modules.logistics.entity.ErpLogisticsEntity;
import com.ziyun.pop.modules.logistics.service.ErpLogisticsService;
import com.ziyun.pop.modules.logistics.vo.ErpLogisticsVo;
import com.ziyun.pop.modules.order.entity.OrderInfoEntity;
import com.ziyun.pop.modules.order.service.ErpOrderService;
import com.ziyun.pop.modules.order.service.OrderInfoService;
import com.ziyun.pop.modules.supp.service.SellerInfoService;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import org.springframework.transaction.annotation.Transactional;


@Service("erpLogisticsService")
public class ErpLogisticsServiceImpl extends ServiceImpl<ErpLogisticsDao, ErpLogisticsEntity> implements ErpLogisticsService {

    @Autowired
    private ErpOrderService erpOrderService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private ErpOrderLogService erpOrderLogService;
    @Autowired
    private SellerInfoService sellerInfoService;

    @Override
    public R queryPage(Map<String, Object> params) {
        int currPage = params.get("page") == null ? 1: StringUtil.objToInt(params.get("page").toString());
        int pageSize = params.get("limit") == null ? 25: StringUtil.objToInt(params.get("limit").toString());
        Page<ErpLogisticsVo> page = new Page<>(currPage,pageSize);

        int totalCounts = baseMapper.countsFinanceList(params);
        page.setTotal(totalCounts);

        Long beginPage = (page.getCurrent() - 1) * page.getSize();
        Long size = page.getSize();

        List<ErpLogisticsVo> list = baseMapper.queryFinanceList(beginPage.intValue(), size.intValue(), params);
        page.setRecords(list);
        List<ErpLogisticsVo> records = page.getRecords();
//        BigDecimal totalAmount = records.stream().filter(erpLogisticsVo->erpLogisticsVo.getLogiCost()!=null)
//                .map(ErpLogisticsVo::getLogiCost)
//                .reduce(BigDecimal.ZERO, BigDecimal::add);

        Double totalAmount = baseMapper.sumLogiCost(params);
        Map<String, Object> userData = new HashMap<>();
        userData.put("totalAmount",totalAmount);
        return R.ok().put("page", new PageUtils(page))
                .put("userData", userData);
    }

    /**
     * 录入成本
     * @param logiId
     * @param logiCost
     * @return
     */
    @Override
    public R enteringCost(Long logiId, double logiCost) {
        ErpLogisticsEntity erpLogisticsEntity = this.baseMapper.selectErpLogisticsById(logiId);
        Integer logisticFinanceStatus = erpLogisticsEntity.getLogisticFinanceStatus();
        if(logisticFinanceStatus.intValue() != LogisticFinanceStatusEnum.NOT_SUBMIT.toInt()
                && logisticFinanceStatus.intValue() != LogisticFinanceStatusEnum.WAIT_AUDIT.toInt()){
            return R.error("当前状态不允许录入成本！");
        }else if(logiCost <= 0){
            return R.error("物流成本需要大于零！");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("logisticFinanceStatus",LogisticFinanceStatusEnum.WAIT_AUDIT.toInt());
        map.put("logiCost",logiCost);
        map.put("updateName", UserUtils.getCurentUser().getUserId());
        baseMapper.updateByMap(map,logiId);
        return R.ok();
    }

    @Override
    public R updateLogisticsInfo(Long logiId, String logiNo) {
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("logiNo", logiNo);
        this.baseMapper.updateByMap(updateMap, logiId);
        return R.ok();
    }

    @Override
    public R updateByMap(Map<String, Object> map) {
        Long logiId =Long.valueOf( map.get("logiId").toString());
        this.baseMapper.updateByMap(map, logiId);
        return R.ok();
    }

    @Override
    public R twbLogisticsPayment(TwbLogisticsPaymentDto twbLogisticsPaymentDto) {
        Integer[] logiIds = twbLogisticsPaymentDto.getLogiIds();
        List<ErpLogisticsEntity> list = baseMapper.selectListByLogiIds(logiIds);
        // 排除已付款物流单据
        List<ErpLogisticsEntity> collect = list.stream().filter(item -> item.getLogisticFinanceStatus() != 2).collect(Collectors.toList());
        if (collect.size() == 0){
            return R.error("未查询到待付款的物流单号");
        }
        List<Integer> ids = collect.stream().map(ErpLogisticsEntity::getLogiId).collect(Collectors.toList());
        Integer[] idArr = new Integer[ids.size()];
        ids.toArray(idArr);
        Map<String, Object> updateMap = new HashMap<>();
        String logiPaytime = twbLogisticsPaymentDto.getLogiPaytime();
        if (StringUtils.isBlank(logiPaytime)){
            logiPaytime = DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        }
        updateMap.put("logiPaytime", logiPaytime);
        updateMap.put("logiPayRemark", twbLogisticsPaymentDto.getLogiPayRemark());
        updateMap.put("logisticFinanceStatus", LogisticFinanceStatusEnum.PAYED.toInt());
        this.baseMapper.updateBatchByMap(updateMap, idArr);

        for (ErpLogisticsEntity erpLogistics: collect){
            String orderNo = erpLogistics.getOrderNo();
            Integer logiId = erpLogistics.getLogiId();
            erpOrderLogService.insertOrderItemLog(orderNo, null, "图文宝物流批量付款：logi_id：" + logiId);
        }

        return R.ok();
    }

    @Override
    @Transactional
    public R saveReceiverInfo(LogisticsReceiverDto logisticsReceiverDto) {
        String orderNo = logisticsReceiverDto.getOrderNo();
        Map<String, Object> updateMap = New.hashMap();
        updateMap.put("shipMobile", logisticsReceiverDto.getToPhone());
        updateMap.put("shipAreaId", logisticsReceiverDto.getToAreaId());
        updateMap.put("shipArea", logisticsReceiverDto.getToArea());
        updateMap.put("shipAddr", logisticsReceiverDto.getToAddress());
        updateMap.put("shipName", logisticsReceiverDto.getToPeople());
        erpOrderService.updateByMap(updateMap, orderNo);

        int count = orderInfoService.count(new QueryWrapper<>(new OrderInfoEntity()).eq("order_id", orderNo));
        if (count > 0){
             orderInfoService.updateByMap(updateMap, orderNo);
        }

        erpOrderLogService.insertOrderItemLog(orderNo, null, "修改收货人地址信息");

        return R.ok();
    }

    @Override
    public R saveShipperInfo(LogisticsShipperDto logisticsShipperDto, Long sellerId) {
        String orderNo = logisticsShipperDto.getOrderNo();
        Map<String, Object> updateMap = New.hashMap();
        updateMap.put("name", logisticsShipperDto.getFromPeople());
        updateMap.put("sellerMobile", logisticsShipperDto.getFromPhone());
        updateMap.put("addr", logisticsShipperDto.getFromAddress());
        updateMap.put("area", logisticsShipperDto.getFromArea());
        updateMap.put("areaId", logisticsShipperDto.getFromAreaId());
        sellerInfoService.updateByMap(updateMap, sellerId);

        erpOrderLogService.insertOrderItemLog(orderNo, null, "修改发货人地址信息");
        return R.ok();
    }

}
